package com.tian.controller;

import com.tian.common.config.AliyunOssService;
import com.tian.common.util.CommonResult;
import com.tian.dto.FileUploadRespDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * {@code @description:} TODO
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2025-03-24 10:54
 * {@code @version:} 1.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Resource
    private AliyunOssService aliyunOssService;

    @PostMapping("/upload")
    @ResponseBody
    public CommonResult<FileUploadRespDto> imgUpdate(@RequestParam("file") MultipartFile file) throws IOException {

        System.out.println("文件上传");


        InputStream is = new ByteArrayInputStream(file.getBytes());

        //文件名
        String trueFileName = file.getOriginalFilename();
        //后缀名
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        //重新命名
        String fileName = System.currentTimeMillis() + suffix;

//        String result = aliyunOssService.uploadFile(fileName, is);
        String result = "http://tianwc.oss-cn-beijing.aliyuncs.com/dev/20250324/1742790089716.png";

        log.info("上传成功，url={}", result);


        if (!result.equals("error")) {
            String[] split = result.split("dev");
            if(split.length>1){
                FileUploadRespDto fileUploadRespDto = new FileUploadRespDto();
                fileUploadRespDto.setFileUrl(split[1]);
                fileUploadRespDto.setFileName(fileName);
                return CommonResult.success(fileUploadRespDto);
            }
        }
        return CommonResult.failed("上传失败");
    }
}
